package com.firstgroup.Utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.firstgroup.domain.User;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

public class JwtUtil {
    //秘钥
    private static final String SigNature = "@1@2#1$!1:>(7)*24(%8*4(&6$4##45@2$%@#";

    //生成Token
    public static String getToken(User user) {
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE, 7);
        Map<String, String> map = new HashMap<>();
        String userId= String.valueOf(user.getId());
        map.put("id",userId);
        map.put("username", user.getUsername());
        map.put("name", user.getName());
        map.put("classId", user.getClassId());
        JWTCreator.Builder builder = JWT.create();
        map.forEach((k, v) -> {
            builder.withClaim(k, v);
        });

        String token = builder.withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(SigNature));


        return token;
    }

    ////验证token
    //public static DecodedJWT Verify(String token) {
    //    return JWT.require(Algorithm.HMAC256(SigNature)).build().verify(token);
    //
    //
    //}

    //验证token
    public static boolean verify(String token) {
        boolean flag=true;
        try {
        JWT.require(Algorithm.HMAC256(SigNature)).build().verify(token);
        }catch (Exception e){
            flag=false;
        }
        return flag;
    }
    //获取token中的信息
    public static DecodedJWT jwtInf(String token){
        DecodedJWT verify = JWT.require(Algorithm.HMAC256(SigNature)).build().verify(token);
        return verify;
    }



}
